<?php
namespace addons\qingdong\controller;
use addons\qingdong\model\Business as BusinessModel;
use addons\qingdong\model\BusinessOther;
use addons\qingdong\model\FormField;
use addons\qingdong\model\Staff;
use addons\qingdong\model\Message;
use addons\qingdong\model\Contract;
use addons\qingdong\model\BusinessStatus;
use addons\qingdong\model\File;
use think\Db;
use think\Exception;
/**
 * 商机接口
 */
class Business extends StaffApi
{
    protected $noNeedLogin = [];
    protected $noNeedRight = [];


    //创建商机
    public function addBusiness()
    {
        $params = $this->request->post();

        $result = FormField::checkFields(FormField::BUSINESS_TYPE, $params);
        if ($result !== true) {
            $this->error($result);
        }
        Db::startTrans();
        try {

            $result = BusinessModel::createBusiness($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('添加商机成功');
        }
    }


    //获取商机列表
    public function getList()
    {
        $limit = input("limit/d", 10);
        $customer_id = input('customer_id');
        $params = $this->request->post();

        $where= FormField::updateWhereField(FormField::BUSINESS_TYPE,$params);

        if (isset($params['createtime']) && $params['createtime']) {//
            $createtime = $params['createtime'];
            $createtime = explode(',', $createtime);
            $where['createtime'] = ['between', [strtotime($createtime[0]), strtotime($createtime[1]) + 86400 - 1]];
        }
        if (isset($params['staff_id']) && $params['staff_id']) {//下级员工筛选
            $where['owner_staff_id'] = $params['staff_id'];
        } else {
            $where['owner_staff_id'] = ['in', Staff::getMyStaffIds()];
            if (isset($params['type']) && $params['type']) {//客户分类
                if ($params['type'] == 1) {//我的创建
                    $where['owner_staff_id'] = $this->auth->id;
                } elseif ($params['type'] == 2) {//下属创建
                    $where['owner_staff_id'] = ['in', Staff::getLowerStaffId()];
                }
            }
        }
        $wheres =[];
        if (isset($params['contract_status']) && $params['contract_status']) {
            if($params['contract_status'] == 1){
                $wheres['contract_status'] = 0;
            }
            if($params['contract_status'] == 2){
                $wheres['contract_status'] = 1;
            }
        }

        if ($customer_id) {
            $where['customer_id'] = $customer_id;
        }
        $records = BusinessModel::where($where)->where($wheres)->with([
            'customer',
            'ownerStaff',
        ])->order('id desc')->paginate($limit)->toArray();
        $data=[];
        foreach($records['data'] as $k=>$v){
            $types = BusinessStatus::where(array('business_id'=>$v['id']))->order('id desc')->value('type');
            if($types){
                $v['type'] = (int)$types;
            }else{
                $v['type'] = 0;
            }
            $data[$k] = $v;
        }
        $allMoney = BusinessModel::where($where)->where($wheres)->sum('money');
        $moneyinfo['repayment_money'] = BusinessModel::where($where)->where(array('contract_status'=>1))->sum('money'); //成交金额
        $moneyinfo['no_money'] = sprintf("%.2f",$allMoney)-sprintf("%.2f",$moneyinfo['repayment_money']);//未成交金额
        $moneyinfo['allmoney'] = $allMoney;//合同总金额
        $this->success('请求成功', ['moneyinfo' => $moneyinfo, 'total' => $records['total'], 'per_page' => $records['per_page'], 'current_page' => $records['current_page'], 'last_page' => $records['last_page'], 'data' => $data]);

    }

    //获取商机详情
    public function getDetail()
    {
        $id = input('id');
        $contract = BusinessModel::where(['id' => $id])->with([
            'customer',
            'ownerStaff',
            'product',
        ])->find();
        if (empty($contract)) {
            $this->error('商机不存在');
        }
        $contract = $contract->toArray();
        $contract = BusinessOther::getOther($contract);
        $type = BusinessStatus::where(array('business_id'=>$contract['id']))->order('id desc')->value('type');
        $contract['type'] = $type ? (int)$type : 0;
        //产品删除不显示
        if(isset($contract['product']) && $contract['product']){
            foreach($contract['product'] as $k=>$v){
                if(!$v['name'] && !$v['num']){
                    unset($contract['product'][$k]);
                }
            }
        }
        //标记通知已读
        Message::setRead(Message::BUSINESS_TYPE, $id, $this->auth->id);

        $this->success('请求成功', $contract);
    }

    //修改商机
    public function editBusiness()
    {
        $id = input('id');
        $params = $this->request->post();
        $row = BusinessModel::where(['id' => $id])->find();
        if (empty($row)) {
            $this->error('商机信息不存在');
        }

        $result = FormField::checkFields(FormField::BUSINESS_TYPE, $params,$id);
        if ($result !== true) {
            $this->error($result);
        }
        Db::startTrans();
        try {
            $result = BusinessModel::updateBusiness($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('修改商机成功');
    }

    /**
     * 转移商机
     */
    public function batch_change()
    {
        $ids = input('id');
        $staff_id = input('owner_staff_id');
        if(!$ids || !$staff_id){
            $this->error('参数不正确');
        }
        $ids = BusinessModel::where([
            'id' => $ids
        ])->column('id');
        if (empty($ids)) {
            $this->error('商机不存在');
        }
        $result = BusinessModel::batchTransfer($ids, $staff_id);
        if(!$result){
            $this->error('操作失败');
        }
        $this->success('操作成功');
    }
    //删除商机
    public function delete()
    {
        $ids = input('id');
        if(!$ids){
            $this->error('参数不正确');
        }
        $data = BusinessModel::where([
            'id' => $ids
        ])->column('id');
        if (empty($data)) {
            $this->error('商机不存在');
        }
        $result = BusinessModel::where(array('id'=>$ids))->update(array('updatetime'=>time(),'deletetime'=>time()));
        if(!$result){
            $this->error('删除失败');
        }
        $this->success('删除成功');
    }
    //关联商机列表
    public function business_list(){
        $ids = input('customer_id');
        if(!$ids){
            $this->error('参数不正确');
        }
        $data= BusinessModel::where(['customer_id'=>$ids,'owner_staff_id'=>['in',Staff::getMyStaffIds()]])->field('id,name')->select();

        $this->success('请求成功',$data);
    }
    //商机合同
    public function contract(){
        $limit = input("limit/d", 10);
        $ids = input('id');
        if(!$ids){
            $this->error('参数不正确');
        }
        $contract = Contract::where(array('business_id'=>$ids))->with([
            'customer',
            'contacts',
            'ownerStaff',
            'orderStaff',
            'receivables'
        ])->order('id desc')->paginate($limit)->toArray();
        $data = isset($contract['data'])?$contract['data']:[];
        if($data){
            foreach ($data as $k => $v) {
                if (empty($v['receivables'])) {
                    $v['receivables'] = [
                        'repayment_money' => 0,
                        'be_money' => $v['money'],
                        'ratio' => 0
                    ];
                } else {
                    $be_money = $v['money'] - $v['receivables']['repayment_money'];
                    $be_money =   ($be_money > 0) ? $be_money : 0;
                    $v['receivables'] = [
                        'repayment_money' => $v['receivables']['repayment_money'],
                        'be_money' =>$be_money,
                        'ratio' => round($v['receivables']['repayment_money'] / $v['money'] * 100, 2)
                    ];
                }
                $data[$k] = $v;
            }
        }
        $this->success('请求成功', ['total' => $contract['total'], 'per_page' => $contract['per_page'], 'current_page' => $contract['current_page'], 'last_page' => $contract['last_page'], 'data' => $data]);

    }
    //商机状态
    public function business_status(){
        $id = input('id');
        $type = input('type',0);
        $remark = input('remark');
        $file = input('file');
        if(!$id){
            $this->error('参数不正确');
        }
        $data = array(
            'id'=>$id,
            'type'=>$type,
            'remark'=>$remark,
            'file'=>$file,
        );
        $business =BusinessModel::batchStatus($data);
        if(!$business){
            $this->error('操作失败');
        }
        $this->success('操作成功');
    }
    //商机历史
    public function business_history(){
        $id = input('id');
        if(!$id){
            $this->error('参数不正确');
        }
        $business = BusinessStatus::where(array('business_id'=>$id))->order('id desc')->select();
        foreach($business as $k=>$v){
            $business[$k]['createtime'] = date('Y-m-d H:i:s',$v['createtime']);
            if($v['file']){
                $business[$k]['file'] = File::where(array('id'=>['in',$v['file']]))->field('id,types,name,save_name,size,file_path')->select();
            }
        }
        $this->success('请求成功',$business);
    }
    //查询商机列表
    public function get_select_list(){
        $limit = input("limit/d", 10);
        $params = $this->request->post();
        $where = [];
        if(isset($params['name']) && $params['name']){
            $where['name'] = array('like','%'.$params['name'].'%');
        }
        $data= BusinessModel::where(['owner_staff_id'=>['in',Staff::getMyStaffIds()]])->where($where)->field('id,name')->order('id desc')->paginate($limit)->toArray();;
        $this->success('请求成功',$data);
    }
}